#!/usr/bin/env bash
set -Eeuo pipefail

# 一键编译 C++ 源码到 out/ 目录（Windows 会生成 .exe）

OS_NAME="${OS:-}"
EXT=""
if [[ "$OS_NAME" == "Windows_NT" ]]; then
  EXT=".exe"
fi

BASE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
OUT_DIR="$BASE_DIR/out"
mkdir -p "$OUT_DIR"

cxx="${CXX:-}"
if [[ -z "$cxx" ]]; then
  for cand in g++ x86_64-w64-mingw32-g++ clang++ c++ cl cl.exe; do
    if command -v "$cand" >/dev/null 2>&1; then
      cxx="$cand"; break
    fi
  done
fi

if [[ -z "$cxx" ]]; then
  echo "[cpp] 未找到可用的 C++ 编译器 (g++/clang++/cl)。"
  echo "     Windows 安装建议:"
  echo "     1) 安装 MSYS2，然后在 \"MSYS2 MinGW x64\" 里执行: pacman -S --needed base-devel mingw-w64-x86_64-gcc"
  echo "     2) 或安装 LLVM/Clang 并将 clang++ 加入 PATH"
  echo "     3) 或安装 Visual Studio Build Tools，并在 Developer Command Prompt 中运行本脚本 (cl)"
  exit 0
fi

CXXFLAGS=${CXXFLAGS:-"-std=c++17 -O2 -Wall -Wextra -Wpedantic"}
echo "[cpp] 使用编译器: $cxx"
echo "[cpp] 输出目录: $OUT_DIR"

shopt -s nullglob
count=0
for src in "$BASE_DIR"/*.cpp; do
  name="$(basename "$src" .cpp)"
  if [[ "$(basename "$cxx")" == "cl" || "$(basename "$cxx")" == "cl.exe" ]]; then
    echo "[cpp] 编译 $name.cpp -> out/${name}.exe (MSVC)"
    "$cxx" /nologo /EHsc /O2 /std:c++17 "$src" /Fe:"$OUT_DIR/${name}.exe"
  else
    echo "[cpp] 编译 $name.cpp -> out/${name}${EXT}"
    "$cxx" $CXXFLAGS "$src" -o "$OUT_DIR/${name}${EXT}"
  fi
  ((count++)) || true
done
shopt -u nullglob

if (( count == 0 )); then
  echo "[cpp] 未发现 .cpp 源文件。"
else
  echo "[cpp] 完成。生成 ${count} 个可执行文件于 out/。"
fi
